package com.dwxt.mall.admin.controller;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.PartyUtil;
import com.dwxt.mall.admin.service.FileServiceAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RequestMapping("/mall/file")
@RestController
public class FileControllerAdmin {

    @Autowired
    private FileServiceAdmin fileService;

    @RequestMapping("/uploadHeadPicture")
    public BaseResult uploadHeadPicture(MultipartFile file) throws IOException {
        String userId = PartyUtil.getCurrentUserId();
        String imgUrl = fileService.saveFile(file, userId);
        return BaseResult.ok(imgUrl);
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/saveFile")
    public BaseResult saveFile(MultipartFile file) throws IOException {
        String fileUrl = fileService.saveFile(file, null);
        return BaseResult.ok(fileUrl);
    }

    /**
     * 上传多个文件
     * @param files
     * @return
     * @throws IOException
     */
    @RequestMapping("/saveFileList")
    public BaseResult saveFileList(List<MultipartFile> files) throws IOException {
        StringBuilder sb = new StringBuilder();
        for (MultipartFile file : files) {
            String fileUrl = fileService.saveFile(file, null);
            sb.append(fileUrl).append(",");
        }
        return BaseResult.ok(sb.deleteCharAt(sb.length() - 1));
    }

}
